/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2023. All rights reserved.
 */
package dao

import (
	"fmt"
	"prim-server/config"
	"prim-server/model"
	"reflect"
	"time"

	"github.com/astaxie/beego/orm"
)

const (
	DefaultOffset    = 0                      //查询时的默认偏移
	DefaultPageSize  = 10                     //查询时的默认页面大小
	TimeFormatLayout = "2006-01-02T15:04:05Z" //UTC时间格式
)

var DBName = config.GetConfig().DBConfig.DBName

func init() {
	orm.RegisterModel(new(model.User))
	orm.RegisterModel(new(model.Role))
	orm.RegisterModel(new(model.CloudUser))
	orm.RegisterModel(new(model.Balance))
	orm.RegisterModel(new(model.BalanceRecord))
	orm.RegisterModel(new(model.Credit))
	orm.RegisterModel(new(model.CreditRecord))
	orm.RegisterModel(new(model.Production))
	orm.RegisterModel(new(model.Bill))
	orm.RegisterModel(new(model.Asset))
	orm.RegisterModel(new(model.OnePayOrder))
	orm.RegisterModel(new(model.OnDemandOrder))
	orm.RegisterModel(new(model.OrderUpdateRecord))
	orm.RegisterModel(new(model.BillUpdateRecord))
	orm.RegisterModel(new(model.TimerTask))
}

type BaseDao struct {
	O orm.Ormer
}

func (dao *BaseDao) Init() {
	dao.O = orm.NewOrm()
}

func (dao *BaseDao) GetDBName() string {
	return DBName
}

func (dao *BaseDao) GetOffsetAndPageSize(queryPage *int, queryPageSize *int) (offset, pageSize int) {
	offset = DefaultOffset
	pageSize = DefaultPageSize
	if queryPage != nil && queryPageSize != nil {
		page := *queryPage
		pageSize = *queryPageSize
		offset := page - 1
		if offset-1 < 0 {
			offset = DefaultOffset
		}
		offset = offset * pageSize
		return offset, pageSize
	}
	return offset, pageSize
}

// 判断数据表是否存在
func (dao *BaseDao) IsExistTable(tableName string) (bool, error) {
	sql := "SHOW TABLES LIKE '" + tableName + "'"
	var res []orm.Params
	_, err := dao.O.Raw(sql).Values(&res)
	if err != nil {
		return false, err
	}
	if len(res) > 0 {
		return true, nil
	}
	return false, nil
}

// 统计所有分表名称
func (dao *BaseDao) GetAllSubTableName(tableName string) ([]string, error) {
	sql := "SHOW TABLES LIKE '" + tableName + "_%'"
	var res []string
	_, err := dao.O.Raw(sql).QueryRows(&res)
	if err != nil {
		return nil, err
	}
	if len(res) > 0 {
		return res, nil
	}
	return nil, nil
}

// 毫秒时间戳转换为UTC时间字符串
func (dao *BaseDao) ConvertToUTC(timeSecond int64) string {
	t := time.UnixMilli(timeSecond).UTC().Format(TimeFormatLayout)
	return t
}

// 拼接SQL插入In的条件，将数组返回为'v1','v2','v3'...的格式
func (dao *BaseDao) JoinArray(arr interface{}) string {
	value := reflect.ValueOf(arr)
	if value.Kind() != reflect.Slice {
		panic("JoinArray: arr is not a slice")
	}
	size := value.Len()
	if size == 0 {
		return ""
	}
	s := ""
	for i := 0; i < size; i++ {
		s += fmt.Sprintf("'%v'", value.Index(i).Interface())
		if i != size-1 {
			s += ","
		}
	}
	return s
}
